/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 15:46:03
 * @Description: 第三步 -- 对公账户信息填写
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Text,
  ScrollView,
  NativeModules,
  SafeAreaView,
  PixelRatio
} from 'react-native';
import { Button, msg, FormInput, AsyncStorage, cache } from '@/common';
import {
  px2dp,
  priceColor,
  mainBgColorWhite,
  fontColorBlack,
  fontColorDeepGray,
  mainBgColorLightGray,
  mainBgColorBlack
} from '@/styles';

import { uploadImage } from '@/config';
import businessApi from '@/api/business';
import Picker from '@/common/picker';
import BusinessFormSelect from './components/business-form-select';

const { Submit } = Button;

export default class CorporateAccountInfoCerti extends React.Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.state = {
      longTimeChecked: false,
      custName: '',
      cardNo: '',
      file: '',
      name: '广发银行',
      curOpenBankName: '',
      curOpenBank: {},
      curBankId: '',
      childBankList: [],
      routerFrom
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.CORPORATE_ACCOUNT_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { CorporateAccountInfoCerti } = dataCache;
      this.setState({ ...CorporateAccountInfoCerti });
    }).catch(err => {
      console.log('对公账户信息反写异常：', err);
    });

    businessApi.findOpenBankIdLikeName().then(res => {
      if (res.success) {
        const childBankList = res.data || [];
        this.setState({
          childBankList,
          curOpenBank: childBankList[0],
          curOpenBankName: childBankList[0].bankNameInfo || '',
          curBankId: childBankList[0].id || ''
        });
      }
    });
    // 监听银行选择
    msg.on('bankDataSelect', (bankDataSelect) => {
      if (bankDataSelect.type === 'openBank') {
        this.setState({ name: bankDataSelect.name });
      }
      if (bankDataSelect.type === 'openBankBranch') {
        this.setState({ curOpenBankName: bankDataSelect.bankNameInfo });
      }
    });
  }

  componentWillUnmount() {
    msg.off('bankDataSelect');
  }

  render() {
    const { custName, cardNo, file, name, curOpenBankName } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          <Text style={styles.stepTip}>第三步</Text>
          <View style={styles.firstPart}>
            <FormInput
              label={this.formItem('开户名称')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入开户名'
              defaultValue={custName}
              inputType={1}
              maxLength={20}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('custName', value);
              }}
            // disabled
            />

            <BusinessFormSelect
              label='开户银行'
              defaultValue='请选择开户银行'
              value={name}
              onPress={this.selectOpenBank}
            />
            <BusinessFormSelect
              label='开户支行'
              defaultValue='请选择支行'
              value={curOpenBankName}
              onPress={this.selectOpenAccountChildBank}
            />

            <FormInput
              label={this.formItem('银行账号')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入银行卡号'
              defaultValue={cardNo}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, borderBottomColor: 'transparent', paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('cardNo', value);
              }}
            // disabled
            />
          </View>
          {/* <View style={styles.licenseBox} >
                        <View style={styles.labelBox}>{this.formItem('业务授权书')}</View>
                        <View style={styles.licenseBtnBox} >
                            <TouchableOpacity
                                onPress={this.selectImage}
                            >
                                {
                                    !!file ?
                                        <Image
                                            style={styles.licenseImgStyle}
                                            source={{ uri: file }}
                                        /> :
                                        <View style={styles.defaultAddBox}>
                                            <Image
                                                style={styles.addImgIcon}
                                                source={iconAdd}
                                            />
                                        </View>
                                }
                            </TouchableOpacity>
                        </View>

                    </View> */}
          <View style={styles.bottomBtnBox}>
            <View style={styles.submitBox}>
              <Submit
                text='上一步'
                btnTextStyle={styles.preStepText}
                boxStyle={styles.preBoxStyle}
                onClick={this.goBack}
              />
            </View>
            <View style={styles.submitBox}>
              <Submit
                text='下一步'
                btnTextStyle={styles.nextStepText}
                boxStyle={styles.nextBoxStyle}
                onClick={this.goNext}
              />
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  formItem = (name) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>{name}</Text>
      </>
    );
  }

  // 选择开户行
  selectOpenBank = () => {
    msg.emit('router: goToNext', {
      routeName: 'B2BCorporateAccountBankSelect',
      type: 'openBank'
    });
  }

  // selectOpenAccountChildBank = () => {
  //     const { childBankList } = this.state;
  //     if (childBankList.length <= 0) return msg.emit('app:tip', { text: '暂无支行信息' });
  //     let pickerL = [];
  //     childBankList.map((item) => {
  //         pickerL.push(item.bankNameInfo);
  //     });
  //     this.showPicker('切换支行', pickerL);
  // }
  // 选择开户支行
  selectOpenAccountChildBank = () => {
    const { name } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'B2BCorporateAccountBankSelect',
      type: 'openBankBranch',
      bankName: name
    });
    // const { childBankList } = this.state;
    // let pickerL = [];
    // childBankList.map((item) => {
    //     pickerL.push(item.bankNameInfo);
    // });
    // this.showPicker('切换支行', pickerL);
  }

  showPicker = (title, dataList) => {
    const { childBankList, curBankId } = this.state;
    let currentName = '';
    childBankList.map((item, index) => {
      if (item.id == curBankId) {
        currentName = item.bankNameInfo;
      }
    });
    Picker.init({
      pickerTitleText: title,
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [currentName],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: dataList,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        childBankList.forEach(item => {
          if (item.bankNameInfo == pickedValue.toString()) {
            this.setState({
              curBankId: item.id,
              curOpenBankName: item.bankNameInfo,
              curOpenBank: item
            });
          }
        });
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
      },
      onPickerSelect: (pickedValue, pickedIndex) => {

      },
    });
    Picker.show();
  };

  goBack = () => {
    msg.emit('router: back');
  }

  goNext = () => {
    const { custName, cardNo, file, name, curOpenBankName, routerFrom } = this.state;
    if (!custName) return msg.emit('app:tip', { text: '请填写开户名称' });
    if (!name) return msg.emit('app:tip', { text: '请选择开户行' });
    if (!curOpenBankName) return msg.emit('app:tip', { text: '请选择开户行支行' });
    // if (!file) return msg.emit('app:tip', { text: '请上传业务授权书' });
    if (!cardNo) return msg.emit('app:tip', { text: '请填写银行卡号' });
    const corporateAccountInfoCertiCache = {
      custName,
      cardNo,
      file,
      name,
      openingBank: curOpenBankName
    };
    const businessCertiString = JSON.stringify({
      CorporateAccountInfoCerti: corporateAccountInfoCertiCache,
    });
    AsyncStorage.setItem(
      cache.CORPORATE_ACCOUNT_INFO_CERTI,
      businessCertiString
    );
    msg.emit('router: goToNext', {
      routeName: 'BusinessManageSetCerti',
      routerFrom
    });
  }

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 选择图片
  selectImage = () => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(path);
    });
  }

  // 上传图片
  IdCardUpload(path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    uploadImage('upload?dirName=businessCert', path).then(res => {
      console.log(`uploadImage：${JSON.stringify(res)}`);
      if (res.success) {
        this.setState({ file: res.data.url });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传失败，请重试',

          isClickBg: false,
          okFn: () => { },
        });
      }
      msg.emit('app:selfTip', {
        isVisible: false,
      });
    }).catch(err => {
      console.log(err);
      msg.emit('app:selfTip', {
        isVisible: false,
      });
      // 请求失败
      msg.emit('app:messageBox', {
        isVisible: true,
        title: '温馨提示',
        text: '上传失败，请重试',

        isClickBg: false,
        okFn: () => { },
      });
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray
  },
  stepTip: {
    color: mainBgColorBlack,
    fontSize: px2dp(28),
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24)
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40)
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38)
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline'
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130)
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40)
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16)
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190)
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10)
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16)
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16)
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  licenseBtnBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190),
    marginTop: px2dp(40),
    paddingLeft: px2dp(32)
  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48)
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: px2dp(40),
    height: px2dp(200),
  },
  submitBox: {
    flex: 1,
    alignItems: 'center'
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764'
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5'
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%'
  }
});
